package Modules::AddCDSs;
use strict;
use warnings;
use Bio::Tools::GFF; 
use Bio::SeqIO;
use Data::Dumper;

sub new {
  my ($class,$util) = @_;
  my $self = {
               util => $util,
             };
  bless $self,$class;
  return $self;
}


sub run {
  my $self        = shift;
  my $orfs        = shift;
  my $util        = $self->{'util'};
  my $source_path = $util->{'SOURCE_PATH'};
  my $data_path   = $util->{'DATA_PATH'};
  my $genome      = $data_path ."/". $util->{'GENOME'};
  my $gtf         = $data_path ."/". $util->{'GTF'}; 
  my $gff_fields  = $util->{'GFF_FIELDS'};
  
  open (my $fh,"<$gtf") or die $!;
  my $gffio = Bio::Tools::GFF->new(-fh => $fh, -version => 2.5);
  
  my ($i,$cdss,$cdss_length,$cdss_start,$cdss_end,$transcript_length,$transcripts,$transcript_start);
  my (@id_transcript,@id_gene,@exon_no,$exons);
  
  while(my $feature = $gffio->next_feature) {
    @id_gene                     = $feature->get_tag_values('gene_id');
    @id_transcript               = $feature->get_tag_values('transcript_id');   
    my ($id_gene,$id_transcript) = ($id_gene[0],$id_transcript[0]);
    my $transcript_start         = $orfs->{$id_transcript}{'transcript_start'};
    my $cdss_start               = $orfs->{$id_transcript}{'cds_start'} + $transcript_start;
    my $cdss_end                 = $orfs->{$id_transcript}{'cds_end'  } + $transcript_start; 
        
    if ($feature->primary_tag eq 'exon') {
      @exon_no       = $feature->get_tag_values('exon_number');
      my $exon_index = $exon_no[0]-1;
      ${$exons->{$id_transcript}}[$exon_index] = $feature;
      
      my $exon_start       = $feature->start;
      my $exon_end         = $feature->end;
      
      my ($CDS_start,$CDS_end);
      
      if ($cdss_start <= $exon_start)                               { $CDS_start = $exon_start ; warn 1}
      if ($cdss_start >= $exon_start && $cdss_start <= $exon_end  ) { $CDS_start = $cdss_start ; warn 2}      
      if ($cdss_end   >= $exon_end  )                               { $CDS_end   = $exon_end   ; warn 3}
      if ($cdss_end   <= $exon_end   && $cdss_end   >= $exon_start) { $CDS_end   = $cdss_end   ; warn 4}      

print "exon_start: $exon_start\texon_end: $exon_end\n"  ;
print "cdss_start: $cdss_start\tcdss_end: $cdss_end\n"  ;
print "CDS_start:  $CDS_start\tCDS_end:  $CDS_end\n\n"  ;

      if ($CDS_start && $CDS_end) {   
        $cdss->{$id_transcript}[$exon_index]{'seq_id'    }       =  $feature->seq_id;
        $cdss->{$id_transcript}[$exon_index]{'source'    }       =  $feature->source_tag;  
        $cdss->{$id_transcript}[$exon_index]{'primary_tag'}      =  'CDS';   
        $cdss->{$id_transcript}[$exon_index]{'CDS_start' }       =  $CDS_start ;        
        $cdss->{$id_transcript}[$exon_index]{'CDS_end'   }       =  $CDS_end   ; 
        $cdss->{$id_transcript}[$exon_index]{'score'}            =  $feature->score;
        $cdss->{$id_transcript}[$exon_index]{'strand'}           =  $feature->strand;
        $cdss->{$id_transcript}[$exon_index]{'frame'}            =  '.';          
      }  
    }
    if ($feature->primary_tag eq 'transcript') { 
      my $cdss_length  = $cdss_end - $cdss_start;

      $transcripts->{$id_transcript}{'feature'}           = $feature;
      $transcripts->{$id_transcript}{'transcript_length'} = $transcript_length;
      $transcripts->{$id_transcript}{'transcript_start'}  = $transcript_start = $feature->start;
      $transcript_length = 0; 
    }

   last if $i++ ==10;
  }
  
  foreach my $transcript (sort {
    my ($aa) = $a =~ /CUFF\.(\d+\.\d+)/; 
    my ($bb) = $b =~ /CUFF\.(\d+\.\d+)/;
    $aa <=> $bb;
    
  } keys %$transcripts) {
    
    my $transc  = $transcripts->{$transcript}{'feature'}; 
      
    print  $transc->gff_string  . "\n";
    map { print $_->gff_string  . "\n"   } @{$exons->{$transcript}}; 
    
    my $CDS_no=0;
    foreach my $CDS (@{ $cdss->{$transcript}}) {
      $CDS_no++;
      foreach my $field (@$gff_fields) {
        print $CDS->{$field}."\t";
      }
      print qq(transcript_id "$transcript"; cds_number "$CDS_no";);
      print "\n";
    } 
  }


}
1;
















=comment  
  my $seqio = new Bio::SeqIO(-format => 'fasta',
                             -file   => $seqfile);
  my $count = 0;
  while( my $seq = $seqio->next_seq ) {
      $count++;
      
      
      my $gffout = new Bio::Tools::GFF(-file        => ">$fname" ,
                                       -gff_version => 1);
      
      foreach my $feature ( $seq->top_SeqFeatures() ) {
      $gffout->write_feature($feature);
      }
  }  

sub run {
  my $self        = shift;
  my $orfs        = shift;
  my $util        = $self->{'util'};
  my $source_path = $util->{'SOURCE_PATH'};
  my $data_path   = $util->{'DATA_PATH'};
  my $genome      = $data_path ."/". $util->{'GENOME'};
  my $gtf         = $data_path ."/". $util->{'GTF'}; 
  
  
  open (my $fh,"<$gtf") or die $!;
  my $gffio = Bio::Tools::GFF->new(-fh => $fh, -version => 2.5);
  
  my ($transcript_length,$id_transcript,$id_gene,$genes,$out,$exons,@transcript);
  my $prev_id_gene;
  my $i;
  
  while(my $feature = $gffio->next_feature()) {
    $id_gene           = $feature->{_gsf_tag_hash}{gene_id}[0];
    $id_transcript     = $feature->{_gsf_tag_hash}{transcript_id}[0];
    
    if ($feature->primary_tag eq 'exon') {
      push @{$exons->{$id_transcript}},$feature->gff_string;
    }
    
    if ($feature->primary_tag eq 'transcript') {
     
      $transcript_length   = $feature->length;
      $genes->{$id_gene}{$transcript_length} = [$id_transcript,$feature->gff_string];
  
    }
    last if $i++ ==1000;
  }
  
  foreach my $gene (keys %$genes) {
    foreach my $transcript_l (sort {$b<=>$a} keys %{$genes->{$gene}}) {
      my $transc_id  = $genes->{$gene}{$transcript_l}[0];
      #print "$gene\t$transc_id\t$transcript_l\n";
      
      print $genes->{$gene}{$transcript_l}[1]."\n";
      map {print "$_\n" } @{$exons->{$transc_id}};
      last;
    }
  }

}
=cut



